package com.rongzhe.house.common.utils;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.rongzhe.house.order.entity.Order;
import com.rongzhe.house.pay.AliPayConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by hggxg on 2018/1/21.
 */
@Component
public class AliPayUtil {

    @Autowired
    private AliPayConfig aliPayConfig;

    //创建订单
    public String[] orderCreate(Order order) throws AlipayApiException {


        AlipayClient alipayClient =
                new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                        aliPayConfig.getAppId(),
                        aliPayConfig.getAppPrivateKey(),
                        "json", aliPayConfig.getCharset(),
                        aliPayConfig.getAlipayPublicKey(),
                        "RSA2");
//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
//SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody(order.getRemark());
        model.setSubject("荣者租房");
        model.setOutTradeNo(order.getCode());
        model.setTimeoutExpress("30m");
        model.setTotalAmount(order.getAmount().toString());
        model.setProductCode("QUICK_MSECURITY_PAY");
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        request.setBizModel(model);
//        request.setNotifyUrl("商户外网可以访问的异步地址");
        AlipayTradeAppPayResponse response;
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            response = alipayClient.sdkExecute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();

            throw e;
        }

        //就是orderString 可以直接给客户端请求，无需再做处理。
        String[] arr = new String[2];

        arr[0] = response.getBody();
        arr[1] = response.getTradeNo();

        return arr;

    }


}
